package cn.tedu.weibo2.service.impl;

import cn.tedu.weibo2.exception.ServiceException;
import cn.tedu.weibo2.mapper.UserMapper;
import cn.tedu.weibo2.pojo.dto.UserLoginDTO;
import cn.tedu.weibo2.pojo.dto.UserRegDTO;
import cn.tedu.weibo2.pojo.entity.User;
import cn.tedu.weibo2.pojo.vo.UserVO;
import cn.tedu.weibo2.response.JsonResult;
import cn.tedu.weibo2.response.StatusCode;
import cn.tedu.weibo2.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private HttpSession session;
    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(UserRegDTO userRegDTO) {
        if (userMapper.selectByUsername(userRegDTO.getUsername())!=null){
            throw new ServiceException(StatusCode.USERNAME_ALREADY_EXISTS);
        }
        User user=new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insert(user);
    }

    @Override
    public UserVO login(UserLoginDTO userLoginDTO) {
        if (userMapper.selectByUsername(userLoginDTO.getUsername())==null){
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }
        UserVO userVO=userMapper.selectForLogin(userLoginDTO);
        if (userVO==null){
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }
        log.debug("数据库返回结果:{}",userVO);
        session.setAttribute("user",userVO);
        return userVO;


    }
}
